﻿using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace Sage.WXWork
{
    /// <summary>
    /// 企业微信加密解密工具类
    /// 提供AES加密解密和网络字节序转换功能
    /// </summary>
    public class Cryptography
    {
        /// <summary>
        /// 将无符号整数从主机字节序转换为网络字节序（大端序）
        /// </summary>
        /// <param name="inval">要转换的无符号整数</param>
        /// <returns>转换后的网络字节序无符号整数</returns>
        public static uint HostToNetworkOrder(uint inval)
        {
            uint outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + (inval >> i * 8 & 255);
            return outval;
        }

        /// <summary>
        /// 将有符号整数从主机字节序转换为网络字节序（大端序）
        /// </summary>
        /// <param name="inval">要转换的有符号整数</param>
        /// <returns>转换后的网络字节序有符号整数</returns>
        public static int HostToNetworkOrder(int inval)
        {
            int outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + (inval >> i * 8 & 255);
            return outval;
        }

        /// <summary>
        /// AES解密方法，用于解密企业微信回调消息
        /// </summary>
        /// <param name="Input">要解密的密文</param>
        /// <param name="EncodingAESKey">AES加密密钥</param>
        /// <param name="corpid">输出参数，解密后的企业ID</param>
        /// <returns>解密后的明文消息</returns>
        /// <exception cref="ArgumentNullException">当输入密文为空时抛出</exception>
        public static string AES_decrypt(string Input, string EncodingAESKey, ref string corpid)
        {
            if (string.IsNullOrEmpty(Input))
                throw new ArgumentNullException(nameof(Input));

            byte[] Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[16];
            Array.Copy(Key, Iv, 16);
            byte[] btmpMsg = AES_decrypt(Input, Iv, Key);

            int len = BitConverter.ToInt32(btmpMsg, 16);
            len = IPAddress.NetworkToHostOrder(len);

            byte[] bMsg = new byte[len];
            byte[] bCorpid = new byte[btmpMsg.Length - 20 - len];
            Array.Copy(btmpMsg, 20, bMsg, 0, len);
            Array.Copy(btmpMsg, 20 + len, bCorpid, 0, btmpMsg.Length - 20 - len);
            string oriMsg = Encoding.UTF8.GetString(bMsg);
            corpid = Encoding.UTF8.GetString(bCorpid);

            return oriMsg;
        }

        /// <summary>
        /// AES加密方法，用于加密企业微信回调消息
        /// </summary>
        /// <param name="Input">要加密的明文消息</param>
        /// <param name="EncodingAESKey">AES加密密钥</param>
        /// <param name="corpid">企业ID</param>
        /// <returns>加密后的密文</returns>
        /// <exception cref="ArgumentNullException">当输入明文为空时抛出</exception>
        public static string AES_encrypt(string Input, string EncodingAESKey, string corpid)
        {
            if (string.IsNullOrEmpty(Input))
                throw new ArgumentNullException(nameof(Input));

            byte[] Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[16];
            Array.Copy(Key, Iv, 16);
            string Randcode = CreateRandCode(16);
            byte[] bRand = Encoding.UTF8.GetBytes(Randcode);
            byte[] bCorpid = Encoding.UTF8.GetBytes(corpid);
            byte[] btmpMsg = Encoding.UTF8.GetBytes(Input);
            byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
            byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bCorpid.Length + btmpMsg.Length];

            Array.Copy(bRand, bMsg, bRand.Length);
            Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
            Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
            Array.Copy(bCorpid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bCorpid.Length);

            return AES_encrypt(bMsg, Iv, Key);
        }

        /// <summary>
        /// 创建指定长度的随机码
        /// </summary>
        /// <param name="codeLen">随机码长度，为0时默认使用16</param>
        /// <returns>生成的随机码字符串</returns>
        private static string CreateRandCode(int codeLen)
        {
            string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
            if (codeLen == 0)
            {
                codeLen = 16;
            }
            string[] arr = codeSerial.Split(',');
            string code = "";
            int randValue;
            Random rand = new(unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
                code += arr[randValue];
            }
            return code;
        }

        /// <summary>
        /// AES加密方法（字符串输入版本）
        /// </summary>
        /// <param name="Input">要加密的字符串</param>
        /// <param name="Iv">初始化向量</param>
        /// <param name="Key">加密密钥</param>
        /// <returns>Base64编码的加密结果</returns>
        private static string AES_encrypt(string Input, byte[] Iv, byte[] Key)
        {
            using var aes = Aes.Create();
            //秘钥的大小，以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff;

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Encoding.UTF8.GetBytes(Input);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = ms.ToArray();
            }
            return Convert.ToBase64String(xBuff);
        }

        /// <summary>
        /// AES加密方法（字节数组输入版本）
        /// 使用自定义PKCS7填充
        /// </summary>
        /// <param name="Input">要加密的字节数组</param>
        /// <param name="Iv">初始化向量</param>
        /// <param name="Key">加密密钥</param>
        /// <returns>Base64编码的加密结果</returns>
        private static string AES_encrypt(byte[] Input, byte[] Iv, byte[] Key)
        {
            using var aes = Aes.Create();
            //秘钥的大小，以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);

            #region 自己进行PKCS7补位，用系统自己带的不行
            byte[] msg = new byte[Input.Length + 32 - Input.Length % 32];
            Array.Copy(Input, msg, Input.Length);
            byte[] pad = KCS7Encoder(Input.Length);
            Array.Copy(pad, 0, msg, Input.Length, pad.Length);
            #endregion

            byte[] xBuff;
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }

            return Convert.ToBase64String(xBuff);
        }

        /// <summary>
        /// PKCS7编码器，用于数据填充
        /// </summary>
        /// <param name="text_length">原始文本长度</param>
        /// <returns>填充字节数组</returns>
        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 32;
            // 计算需要填充的位数
            int amount_to_pad = block_size - text_length % block_size;
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            // 获得补位所用的字符
            char pad_chr = Chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp += pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }

        /// <summary>
        /// 将数字转化成ASCII码对应的字符，用于对明文进行补码
        /// </summary>
        /// <param name="a">需要转化的数字</param>
        /// <returns>转化得到的字符</returns>
        static char Chr(int a)
        {
            byte target = (byte)(a & 0xFF);
            return (char)target;
        }

        /// <summary>
        /// AES解密方法（私有实现）
        /// </summary>
        /// <param name="Input">Base64编码的密文</param>
        /// <param name="Iv">初始化向量</param>
        /// <param name="Key">解密密钥</param>
        /// <returns>解密后的字节数组</returns>
        private static byte[] AES_decrypt(string Input, byte[] Iv, byte[] Key)
        {
            using var aes = Aes.Create();
            aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.Key = Key;
            aes.IV = Iv;
            var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            byte[] xBuff;

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Convert.FromBase64String(Input);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = Decode2(ms.ToArray());
            }
            return xBuff;
        }

        /// <summary>
        /// 解码方法，用于移除PKCS7填充
        /// </summary>
        /// <param name="decrypted">解密后的字节数组</param>
        /// <returns>移除填充后的字节数组</returns>
        private static byte[] Decode2(byte[] decrypted)
        {
            int pad = decrypted[^1];
            if (pad < 1 || pad > 32)
            {
                pad = 0;
            }
            byte[] res = new byte[decrypted.Length - pad];
            Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
            return res;
        }
    }
}
